package controllers;

import helpers.HeaderHelper;
import helpers.ItuneJsonUrlHelper;
import helpers.SoftwareHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import crawlers.CrawlerItuneJson;
import crawlers.CrawlerItuneXML;
import debug.SoftwareDebug;

import models.Software;

public class InfoApp extends HttpServlet {
	
	private List<String> blacklist = new ArrayList<String>(Arrays.asList("376631311"));
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		response.setHeader("Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//Set header page
		HeaderHelper headerHelper = new HeaderHelper();
		ArrayList<Software> softwares = new ArrayList<Software>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = SoftwareHelper.getIdFromInfoUrl(path.toLowerCase().replaceAll("/i/", ""));
		//Set cache
        Cache cache=null;
        String cachename = "infoapp_" + id;
        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        
        //Check blacklist
        if (blacklist.contains(id)) {
        	response.sendRedirect("/home");
        	return;
        }
        
        if (cache.containsKey(cachename)) {
        	softwares = (ArrayList<Software>) cache.get(cachename);
        	System.out.println("softwares: cache print");
        } else {
        	softwares = CrawlerItuneJson.getJson(ItuneJsonUrlHelper.getUrlById(id));
        	if (softwares.size() > 0) {
        		cache.put(cachename, softwares);
        	}
	        System.out.println("softwares: Data print");
        }
		
        if (softwares.size() > 0 ) {
        	Software software = softwares.get(0);
        	headerHelper.setTitle(software.getTrackName() + " - 1stApp.org");
        	headerHelper.setKeywords("");
        	headerHelper.setDescription(StringHelper.cutString(StringHelper.html2text(software.getDescription().getValue()).replace("\"", ""), 100));
        	headerHelper.setOgite_name(software.getTrackName() + " - 1stApp.org");
        	headerHelper.setOgtitle(software.getTrackName() + " - 1stApp.org");
        	headerHelper.setOgimage(software.getArtworkUrl60());
        	headerHelper.setOgurl("http://www.1stapp.org/i/" + StringHelper.getAlias(software.getTrackName()) + "-" + software.getTrackId());
        	headerHelper.setOgescription(StringHelper.cutString(StringHelper.html2text(software.getDescription().getValue()).replace("\"", ""), 100));
        } else {
        	response.sendRedirect("/home");
        }
        //SoftwareDebug.debug(softwares.get(0));
		//Set variable to fronted
		request.setAttribute("headerHelper", headerHelper);
		request.setAttribute("softwares", softwares);
		
		try {
			request.getRequestDispatcher("/pages/app_info.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String str = "Don't 100 !! - Do not say the 100 -";
		System.out.println(str.replaceAll("[^0-9a-zA-Z ]", "").replace(" ", "-").toLowerCase());
	}
}
